<template>
	<view class="main">
		<view class="example">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" label-position="top">
				<uni-forms-item label="baseUrl" required name="baseUrl">
					<uni-easyinput v-model="valiFormData.baseUrl" placeholder="请输入baseUrl" />
				</uni-forms-item>
				<uni-forms-item label="用户名" required name="userName">
					<uni-easyinput v-model="valiFormData.userName" placeholder="请输入用户名" />
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="submit('valiForm')">提交</button>
		</view>
	</view>

</template>

<script>
	const app = getApp({allowDefault: true});
	export default {
		data() {
			return {
				rules: {
					baseUrl: {
						rules: [{
							required: true,
							errorMessage: 'baseUrl不能为空'
						}]
					},
					userName: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空'
						}]
					},
				},
				valiFormData: {
					userName: "",
					baseUrl: 'http://10.174.255.176:5000'
					//baseUrl: 'https://cea9-202-104-64-42.ngrok-free.app'
				}

			}
		},
		created() {
      const baseUrl = uni.getStorageSync("baseUrl");
      if(baseUrl){
        // this.valiFormData.baseUrl = baseUrl
      }
      
    },
		methods: {
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					uni.request({
						url: `${res.baseUrl}/api/getMyContact`,
            header:{
              'ngrok-skip-browser-warning': 'true'
            },
						data: {
							username: res.userName
						},
						success: (data) => {
							console.log(data, "data")

							const result = data.data.data;
							if (Array.isArray(result)) {
								uni.showToast({
									title: "登录成功"
								})
								const myContactList = result.map((item, index) => {
									return {
										index: index,
										name: item,
                    label: item.replace("###", '')
									}
								})
								uni.setStorageSync('myContactList', JSON.stringify(myContactList));
								uni.setStorageSync("userName", res.userName)
								app.globalData.userName = res.userName;
								uni.setStorageSync("baseUrl", res.baseUrl)
								app.globalData.baseUrl = res.baseUrl;
								uni.navigateTo({
									url: `/pages/index/index`
								});
							} else {
								uni.showToast({
									title: result
								})
							}


						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style>
	page {
		background-color: #fff;
	}

	.btn-box {}

	.main {
		margin: 100rpx 20rpx;
	}
</style>